package org.wenhua.yuan.and.views.tab_fragment;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TabBtnFragmentLayout extends FrameLayout {

    private TabBtnFragmentAdapter btnFragmentAdapter;
    private int curPosition; // 记录当前position的fragment

    public TabBtnFragmentLayout(@NonNull Context context) {
        this(context, null);
    }

    public TabBtnFragmentLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabBtnFragmentLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.initTabBtnFragment(context, attrs, defStyleAttr);

    }

    private void initTabBtnFragment(Context context, AttributeSet attrs, int defStyleAttr) {

    }


    public void setAdapter(TabBtnFragmentAdapter adapter) throws IllegalAccessException {
        if (adapter == null) throw new IllegalAccessException("TabBtnFragmentAdapter 传入实例并不能为空");
        this.btnFragmentAdapter = adapter;
        this.curPosition = -1;
        setCurrentItem(0);//设置默认显示tab-fragment
    }

    public void setCurrentItem (int position) {

        if (btnFragmentAdapter == null || position < 0 || position > btnFragmentAdapter.getTotalCount() -1){
            return;
        }
        if (position != curPosition) {
            // 避免重复执行instantiateItem
            curPosition = position;
            btnFragmentAdapter.instantiateItem(this, position);
        }
    }
}
